﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace Kotonoha.Client.Settings {
    internal class ClientSettings {
        private static ClientSettings instance;

        public static ClientSettings Instance {
            get {
                lock (typeof(ClientSettings)) {
                    if (instance == null) {
                        instance = new ClientSettings();
                    }
                    return instance;
                }
            }
        }

        private ClientSettings() {
            RegistryKey user = Registry.CurrentUser;
            RegistryKey programs = user.OpenSubKey("Software", false);
            using (RegistryKey key = programs.OpenSubKey("Kotonoha")) {
                foreach (var variable in variables) {
                    variable.load(key);
                }
            }
            programs.Close();
        }

        public void save() {
            RegistryKey user = Registry.CurrentUser;
            RegistryKey programs = user.OpenSubKey("Software", true);
            using (RegistryKey key = programs.CreateSubKey("Kotonoha")) {
                foreach (var variable in variables) {
                    variable.save(key);
                }
            }
            programs.Close();
        }

        private static Variable[] variables = new[] {
                                                        new Variable("InstallDir", RegistryValueKind.String, null)
                                                    };

        public string InstallDir {
            get { return variables[0].Get<string>(); }
            set { variables[0].Set(value);}
        }

    }

    internal class Variable {
        private readonly string name;
        private readonly RegistryValueKind type;
        private object data;

        public Variable(string name, RegistryValueKind type, object defVal) {
            this.name = name;
            this.type = type;
            data = defVal;
        }

        public T Get<T>() {
            return (T) data;
        }

        public void Set(object val) {
            data = val;
            Changed = true;
        }

        public void load(RegistryKey key) {
            data = key.GetValue(name, data);
        }

        public void save(RegistryKey key) {
            if (Changed) {
                key.SetValue(name, data, type);
            }
        }

        public bool Changed { get; private set; }
    }
}